<template>
	<view class="popup-overlay" v-if="show">
		<view class="popup" @click.stop>
			<view class="coupon-settings">
				<view class="close-button" @click="close">×</view>
				<view class="input-group">
					<text class="label">优惠券名称：</text>
					<input class="input-field" type="text" v-model="coupon.name" placeholder="输入优惠券名称" />
				</view>
				<view class="select-group">
					<text class="label">优惠券类型：</text>
					<picker ref="picker" mode="selector" :range="Object.keys(types)" @change="onTypeChange">
						<view class="picker-custom">
							<view class="picker-selected">{{ Object.keys(types)[typesIndex] }}</view>
							<view class="picker-arrow"></view>
						</view>
					</picker>
				</view>
				<!-- 根据 coupon.type 动态切换显示面额或折扣输入框 -->
				<view v-if="coupon.type === 'reward'" class="input-group">
				    <text class="label">优惠券面额：</text>
				    <input class="input-field" type="number" v-model="coupon.money" placeholder="输入优惠券面额" />
				</view>
				
				<view v-if="coupon.type === 'discount'" class="input-group">
				    <text class="label">优惠券折扣：</text>
				    <input class="input-field" type="number" v-model="coupon.discount" placeholder="输入优惠券折扣(0.01-1之间)" @input="validateDiscount" />
				</view>
				<view class="input-group">
					<text class="label">输入满多少元可以使用：</text>
					<input class="input-field" type="number" v-model="coupon.atleast" placeholder="输入最低使用金额" />
				</view>
				<view class="select-group">
					<text class="label">允许直接领取：</text>
					<picker mode="selector" :range="['是', '否']" @change="onDirectChange">
						<view class="picker-custom">
							<view class="picker-selected">{{ coupon.isshow === 1 ? '是' : '否' }}</view>
							<view class="picker-arrow"></view>
						</view>
					</picker>
				</view>
				<view class="select-group">
					<text class="label">过期类型：</text>
					<picker mode="selector" :range="validitytypes" @change="onExpiryTypeChange">
						<view class="picker-custom">
							<view class="picker-selected">{{ coupon.validitytype }}</view>
							<view class="picker-arrow"></view>
						</view>
					</picker>
				</view>
				<view class="input-group" v-if="coupon.validitytype !== '长期有效'">
					<text class="label">使用结束时间：</text>
					<picker mode="date" @change="onDateChange">
						<view class="picker-custom">
							<view class="picker-selected">{{ coupon.endusetime }}</view>
							<view class="picker-arrow"></view>
						</view>
					</picker>
				</view>
				<view class="input-group">
					<text class="label">发放数量：</text>
					<view class="count-controls">
						<button class="count-button" @click="decreaseCount">-</button>
						<input class="input-field count" type="number" v-model.number="coupon.count" />
						<button class="count-button" @click="increaseCount">+</button>
					</view>
				</view>
				<!-- 新增每人最大领取数量 -->
				<view class="input-group">
					<text class="label">每人最大领取数量：</text>
					<view class="count-controls">
						<button class="count-button" @click="decreaseMaxFetch">-</button>
						<input class="input-field count" type="number" v-model.number="coupon.maxfetch" />
						<button class="count-button" @click="increaseMaxFetch">+</button>
					</view>
				</view>
				<button class="confirm-button" @click="confirmSettings">确认添加</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		show: Boolean,
	},
	data() {
		return {
			coupon: {
				name: '',
				money: 100,
				atleast: 200,
				type: 'reward',
				isshow: 0, // 默认不允许直接领取
				validitytype: '长期有效',
				endusetime: '', // 默认空字符串
				count: 1, // 默认发放数量为 1
				maxfetch: 1, // 默认每人最大领取数量为 1
				discount: '',   // 优惠券折扣
			},
			types: {
				'满减': 'reward',
				'折扣': 'discount'
			},
			typesIndex: 0, // 默认索引
			validitytypes: ['固定时间范围过期', '领取之日起', '长期有效'],
		};
	},
	created() {
		const today = new Date();
		today.setDate(today.getDate() + 10);
		this.coupon.endusetime = today.toISOString().split('T')[0];
		this.typesIndex = 0; // 设置默认索引
		this.coupon.type = Object.values(this.types)[this.typesIndex]; // 默认选中第一个类型
	},
	methods: {
		close() {
			this.$emit('close'); // 触发父组件事件关闭弹窗
		},
		onTypeChange(e) {
			const index = e.detail.value;
			this.typesIndex = index; // 更新类型索引
			this.coupon.type = Object.values(this.types)[index]; // 更新优惠券类型
		},
		onDirectChange(e) {
			// 更新直接领取选项，设置为 1（是）或 0（否）
			const index = parseInt(e.detail.value);
			this.coupon.isshow = index === 0 ? 1 : 0;
		},
		onExpiryTypeChange(e) {
			this.coupon.validitytype = this.validitytypes[e.detail.value];
			if (this.coupon.validitytype === '长期有效') {
				this.coupon.endusetime = ''; // 清空结束时间
			}
		},
		onDateChange(e) {
			this.coupon.endusetime = e.detail.value;
		},
		increaseCount() {
			this.coupon.count = Number(this.coupon.count) + 1; // 确保操作的是数字
		},
		decreaseCount() {
			if (this.coupon.count > 0) {
				this.coupon.count = Number(this.coupon.count) - 1; // 确保操作的是数字
			}
		},
		// 新增增加与减少 maxfetch 的方法
		increaseMaxFetch() {
			this.coupon.maxfetch = Number(this.coupon.maxfetch) + 1; // 确保操作的是数字
		},
		decreaseMaxFetch() {
			if (this.coupon.maxfetch > 0) {
				this.coupon.maxfetch = Number(this.coupon.maxfetch) - 1; // 确保操作的是数字
			}
		},
		// 验证折扣输入，确保最多两位小数
		    validateDiscount(event) {
		        let value = event.target.value;
		        // 只允许最多两位小数
		        value = value.replace(/[^0-9.]/g, ''); // 去除非数字和小数点的字符
		        const parts = value.split('.');
		        if (parts.length > 1) {
		            parts[1] = parts[1].substring(0, 2); // 保留最多两位小数
		            value = parts.join('.');
		        }
		        this.coupon.discount = value; // 更新折扣值
		    },
		confirmSettings() {
			if (!this.coupon.name || this.coupon.money <= 0) {
				uni.showToast({
					title: '请完整填写优惠券信息',
					icon: 'none'
				});
				return;
			}
			
			// 检查折扣是否在合法范围内
			if (this.coupon.type === 'discount') {
			    if (this.coupon.discount < 0.01 || this.coupon.discount >= 1) {
			        uni.showToast({
			            title: '折扣值必须在0.01到1之间',
			            icon: 'none'
			        });
			        return;
			    }
			}

			// 如果是固定时间范围过期，校验结束时间
			if (this.coupon.validitytype === '固定时间范围过期' && !this.coupon.endusetime) {
				uni.showToast({
					title: '请选择使用结束时间',
					icon: 'none'
				});
				return;
			}

			// 提交数据
			this.addData();
		},
		addData() {
			this.$xyfun.userStoreId().then((store_id) => {
				this.coupon.store_id = store_id;
				this.$api.post({
					url: '/Coupon/addCoupon',
					loadingTip: '加载中...',
					data: {
						...this.coupon
					},
					success: (res) => {
						uni.stopPullDownRefresh();
						this.$emit('close'); // 关闭弹窗
						uni.showToast({
							title: '优惠券添加成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						uni.showToast({
							title: '添加失败，请重试',
							icon: 'none'
						});
					}
				});
			});
		}
	}
};
</script>


<style scoped>
.popup-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: auto;
}

.popup {
	background-color: #fff;
	width: 80%;
	border-radius: 10px;
	padding: 20px;
}

.coupon-settings {
	padding: 20px;
	background-color: #fff;
}

.close-button {
	position: absolute;
	top: 10px;
	right: 30px;
	width: 24px;
	height: 24px;
	line-height: 24px;
	text-align: center;
	background-color: #000;
	color: #fff;
	border-radius: 50%;
	font-size: 18px;
	cursor: pointer;
}

.close-button:hover {
	background-color: #d32f2f;
}

.input-group,
.select-group {
	margin-bottom: 15px;
}

.label {
	display: block;
	margin-bottom: 5px;
	color: #333;
}

.input-field {
	width: 100%;
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 5px;
}

.picker-custom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 5px;
	background-color: #F5F5F5;
}

.picker-selected {
	flex: 1;
	color: #333;
}

.picker-arrow {
	width: 0;
	height: 0;
	border-left: 5px solid transparent;
	border-right: 5px solid transparent;
	border-top: 5px solid #000;
	margin-left: 10px;
}

.count-controls {
	display: flex;
	align-items: center;
	justify-content: center;
	/* 水平居中 */
}

.count-button {
	width: 30px;
	height: 30px;
	line-height: 30px;
	font-size: 18px;
	text-align: center;
	background-color: #ccc;
	border: none;
	border-radius: 5px;
	margin: 0 10px;
	cursor: pointer;
}

.count-button:hover {
	background-color: #aaa;
}

.count {
	font-size: 16px;
	color: #333;
}

.confirm-button {
	width: 100%;
	height: 40px;
	line-height: 40px;
	background-color: #65C61D;
	color: #fff;
	border: none;
	border-radius: 14px;
	font-size: 16px;
	cursor: pointer;
}

.confirm-button:hover {
	background-color: #45a049;
}

.input-field.count {
	width: 60px;
	text-align: center;
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 5px;
}
</style>
